package com.kl.drs.task;

import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.kl.drs.bean.bo.CheckResultBO;
import com.kl.drs.bean.bo.DrsAsynchTaskBO;
import com.kl.drs.common.BusinessKey;
import com.kl.drs.service.CheckResultService;
import com.kl.drs.service.DrsAsynchTaskService;
import com.kl.drs.util.ConfigsUtil;
import com.kl.drs.util.Log4jUtils;
/**
 * 核心双录数据同步
 * @author ThinkPad
 *
 */
@Component
@Configuration
@EnableScheduling
public class TaskCheckInfoSynchJob {
	
	@Autowired
	private CheckResultService checkResultService;
	
	@Autowired
	private DrsAsynchTaskService drsAsynchTaskService;
	private static int THREAD_MAX_COUNT = 1;
	private static int currentCount = 0;
	//每天晚上22点定时执行
	@Scheduled(cron= " 0 0 22 * * ? ")
	@Async
	public void excute(){
		Log4jUtils.logDebug("@Scheduled-------TaskCheckInfoSynchJob.excute()---start:"+"\t\t" + new Date(System.currentTimeMillis()));
		if(currentCount<THREAD_MAX_COUNT){
			currentCount++;
			Log4jUtils.logDebug("TaskCheckInfoSynchJob.excute() business start:"+"\t\t" + new Date(System.currentTimeMillis()));
			try {
				//查询核心数据库获取需双录保单
				ExecutorService executor = Executors.newSingleThreadExecutor();  
		        FutureTask<List> future = new FutureTask<List>(new Callable<List>(){  
		        public List call() throws Exception {  
		            	List<CheckResultBO> checkResultList=checkResultService.getCheckResultList(BusinessKey.DR_FLAG);
		            	return checkResultList;
		            }  
		        });  
		        executor.execute(future);  
		        try {
		        	CheckResultBO checkResultBO;
		            List<CheckResultBO> checkResultList = future.get(30000, TimeUnit.MILLISECONDS);
		            for (CheckResultBO checkResult : checkResultList) {
						String businessNo = checkResult.getContno();
						try{
							Log4jUtils.logDebug(checkResult.getContno()+"添加开始：");
							checkResultBO=new CheckResultBO();
							checkResultBO.setBusinessNo(businessNo);
							checkResultBO.setSignDate(checkResult.getSignDate());
							checkResultBO.setCrsSalechnl(checkResult.getCrsSalechnl());
							checkResultBO.setBankCode(ConfigsUtil.getProperty("insurer.code", ""));
							String res = checkResultService.createOrUpdateCheckResult(checkResultBO);
							if(!"fail".equalsIgnoreCase(res)){
								Log4jUtils.logDebug(checkResultBO.getBusinessNo()+"添加成功！");
							}else{
								Log4jUtils.logDebug(checkResultBO.getBusinessNo()+"添加失败！");
							}
							if("add".equalsIgnoreCase(res)){
								DrsAsynchTaskBO drsAsynchTaskBO = new DrsAsynchTaskBO();
								drsAsynchTaskBO.setBusinessNo(checkResultBO.getBusinessNo());
								drsAsynchTaskBO.setTaskType(BusinessKey.ASYNCH_TYPE_CR);
								drsAsynchTaskBO.setStatus(BusinessKey.ASYNC_TASK_STATUS_WAIT);
								drsAsynchTaskService.addAsynchTask(drsAsynchTaskBO);
							}
						}catch(Exception ex){
							Log4jUtils.logError("TaskCheckInfoSynchJob.excute()", businessNo+"核心数据同步异常----TaskCheckInfoSynchJob.excute(),错误："+ex.getMessage(), ex);
						}
							}
		            
				        } catch (InterruptedException e) {  
				            // TODO Auto-generated catch block  
				        	Log4jUtils.logError("TaskCheckInfoSynchJob.excute()","@Scheduled-------TaskCheckInfoSynchJob.InterruptedException(),错误："+e.getMessage(),e);  
				        } catch (ExecutionException e) {  
				            // TODO Auto-generated catch block  
				        	Log4jUtils.logError("TaskCheckInfoSynchJob.excute()","@Scheduled-------TaskCheckInfoSynchJob.ExecutionException(),错误："+e.getMessage(),e); 
				        } catch (TimeoutException e) {  
				            // TODO Auto-generated catch block  
				        	Log4jUtils.logError("TaskCheckInfoSynchJob.excute()","@Scheduled-------TaskCheckInfoSynchJob.TimeoutException(),错误："+e.getMessage(),e); 
				        }finally{  
				            future.cancel(true);  
				            executor.shutdown();     
				        } 
					} catch (Exception e) {
				Log4jUtils.logError("TaskCheckInfoSynchJob.excute()","@Scheduled-------TaskCheckInfoSynchJob.excute(),错误："+e.getMessage(),e);
			}finally{
				currentCount--;
			}
			Log4jUtils.logDebug("TaskCheckInfoSynchJob.excute()---business end:"+"\t\t" + new Date(System.currentTimeMillis()));
		}
		Log4jUtils.logDebug("@Scheduled-------TaskCheckInfoSynchJob.excute()---end:"+"\t\t" + new Date(System.currentTimeMillis()));
	}
}
